package com.example.customer;

import cn.hutool.core.lang.Validator;
import com.example.client.FraudService;
import com.example.client.FraudReviewResponse;
import com.example.client.NotificationRequest;
import com.example.customer.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Optional;

@Service
@Slf4j
public record CustomerService(
        CustomerRepository customerRepository,
        FraudService fraudService,
        RabbitMQMessageProducer rabbitMQMessageProducer,  // 替换NotificationService
        NotificationConfig notificationConfig) {

    public void registerCustomer(CustomerRegistryRequest request) {
        log.info("开始注册客户: {}", request);

        // 检查email是否有效
        if (request.email() == null || !Validator.isEmail(request.email())) {
            log.error("注册失败: email地址无效 - {}", request.email());
            throw new ApiException("邮箱格式不正确");
        }

        // 检查email是否已经注册
        Optional<Customer> existEmail = customerRepository.findByEmail(request.email());
        if (existEmail.isPresent()) {
            log.error("注册失败: 邮箱已存在 - {}", request.email());
            throw new ApiException("邮箱已被注册");
        }

        // 构建Customer对象
        Customer customer = Customer.builder()
                .name(request.name())
                .email(request.email())
                .build();

        // 调用fraud服务进行征信检查
        log.info("调用fraud服务检查用户征信: {}", request.email());
        FraudReviewResponse fraudReviewResponse = fraudService.isFraudster(request.email());

        if (Boolean.TRUE.equals(fraudReviewResponse.isFraudster())) {
            log.error("注册失败: 用户存在征信问题 - {}", request.email());
            throw new ApiException("用户存在征信问题，注册被拒绝");
        }

        // 存入数据库
        Customer savedCustomer = customerRepository.save(customer);
        log.info("注册成功: {}", savedCustomer);

        // 构建通知请求
        NotificationRequest notificationRequest = new NotificationRequest(
                "尊敬的 " + savedCustomer.getName() + "，欢迎您选择Example银行！您的账户已成功创建。",
                savedCustomer.getEmail(),
                savedCustomer.getId()
        );

        // 通过消息队列发送通知
        rabbitMQMessageProducer.publish(
                notificationRequest,
                notificationConfig.getInternalExchange(),
                notificationConfig.getInternalNotificationRoutingKey()
        );

        log.info("用户注册流程完成");
    }

    public Customer getCustomerById(Integer id) {
        return customerRepository.findById(id)
                .orElseThrow(() -> new ApiException("客户不存在，ID: " + id));
    }
}